package com.java.userservice.service.impl;

import com.java.common.model.Result;
import com.java.userservice.dao.RolePermissionMapper;
import com.java.userservice.model.dto.RolePermissionDTO;
import com.java.userservice.model.RolePermission;
import com.java.userservice.service.RolePermissionService;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<RolePermission> list(int roleId) {
        return rolePermissionMapper.list(roleId);
    }

    @Transactional
    @Override
    public Result save(RolePermissionDTO rolePermissionDTO) {
        // 1.删除该角色原有的权限
        rolePermissionMapper.removeByRoleId(rolePermissionDTO.getRoleId());
        // 2.如果有勾选权限， 则为该角色添加权限
        if (!ArrayUtils.isEmpty(rolePermissionDTO.getPermissionIds())) {
            for (int permissionId : rolePermissionDTO.getPermissionIds()) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(rolePermissionDTO.getRoleId());
                rolePermission.setPermissionId(permissionId);
                rolePermissionMapper.save(rolePermission);
            }
        }
        return Result.success();
    }
}
